package com.ibeetl.admin.core.service;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ibeetl.admin.core.web.JsonResult;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ibeetl.admin.core.conf.PasswordConfig;
import com.ibeetl.admin.core.conf.PasswordConfig.PasswordEncryptService;
import com.ibeetl.admin.core.dao.CoreOrgDao;
import com.ibeetl.admin.core.dao.CoreUserDao;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.enums.DelFlagEnum;
import com.ibeetl.admin.core.util.enums.GeneralStateEnum;

@Service
@Transactional
public class CoreUserService {
	@Autowired
	CoreUserDao userDao ;
	
	@Autowired
	CoreOrgDao orgDao;
	
	@Autowired
	PasswordEncryptService passwordEncryptService;
	
	@Autowired SQLManager sqlManager;
	
	public UserLoginInfo login(String userName,String password,Long orgId){
		CoreUser query = new CoreUser();
        String pwd = stringToMD5(password);
		query.setCode(userName);
		query.setPassword(passwordEncryptService.password(pwd));
		query.setState(GeneralStateEnum.ENABLE.getValue());
		CoreUser user =userDao.createLambdaQuery().andEq(CoreUser::getCode,userName).
		    andEq(CoreUser::getPassword, passwordEncryptService.password(pwd)).single();
		if(user==null) {
		    throw new PlatformException("用户"+userName+"不存在或者密码错误");
		}

		if(!user.getState().equals(GeneralStateEnum.ENABLE.getValue())){
		    throw new PlatformException("用户"+userName+"已经失效");
		}
		if(user.getDelFlag()==DelFlagEnum.DELETED.getValue()) {
		    throw new PlatformException("用户"+userName+"已经删除");
		}
		List<CoreOrg>  orgs = getUserOrg(user.getId(),user.getOrgId());
		UserLoginInfo loginInfo = new UserLoginInfo();
        if(user.getOrgId()!=orgId) {
            loginInfo.setCurrentOrg(null);
        }else{
            loginInfo.setCurrentOrg(orgs.get(0));
        }
        loginInfo.setOrgs(orgs);
		loginInfo.setUser(user);
		return loginInfo;
	}

	/**
	 * 将密码加密成MD5
	 * @param password 密码
	 * @return pwd MD5加密后的字符串
	 */

	public String stringToMD5(String password){
		String pwd = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(password.getBytes());
			pwd = new BigInteger(1,md.digest()).toString(16);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return pwd;
	}

	public String getDateRange(CoreUser user){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(user.getValidStartDate()).toString()+" 至 "+sdf.format(user.getValidEndDate()).toString();
        return  dateStr;
    }

	public  Date getDate(String dateRange,String returnType){
		String[] dateStr = null;
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
		dateStr=dateRange.split("至");
		if(returnType.equals("0")){
            try {
                date = sdf.parse(dateStr[0].trim());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else{
            try {
                date = sdf.parse(dateStr[1].trim());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
		return date;
	}

    public String check(String userName,String password,Long orgId) throws NoSuchAlgorithmException {
	    String error = "";
        CoreUser query = new CoreUser();
        String pwd = stringToMD5(password);
        query.setCode(userName);
        //query.setPassword(passwordEncryptService.password(pwd));
        query.setState(GeneralStateEnum.ENABLE.getValue());
//        CoreUser user =userDao.createLambdaQuery().andEq(CoreUser::getCode,userName).
//                andEq(CoreUser::getPassword, passwordEncryptService.password(pwd)).single();
        CoreUser user =userDao.createLambdaQuery().andEq(CoreUser::getCode,userName).single();
        error="0";
        if(user==null) {
            return "1";
        }else if(!user.getPassword().equals(pwd)){
            if(user.getFailCount()==5){
                user.setState("S3");
                user.setFailCount(Long.valueOf(0));
                userDao.updateById(user);
                return "3";
            }
            user.setFailCount(user.getFailCount()+1);
            userDao.updateById(user);
            return "2";
        }else if(user.getState().equals("S3")){
            return "3";
        }else if(!user.getState().equals(GeneralStateEnum.ENABLE.getValue())){
            return "4";
        }else if(user.getDelFlag()==DelFlagEnum.DELETED.getValue()) {
            return "5";
        }else if(user.getOrgId()!=orgId) {
            return "6";
        }else if(user.getValidStartDate().compareTo(new Date())==1||user.getValidEndDate().compareTo(new Date())==-1){
			return "7";
		}

		if(error.equals("0")){
            user.setFailCount(Long.valueOf(0));
            userDao.updateById(user);
        }

        return error;
    }
	
	
	
	public  List<CoreOrg> getUserOrg(long userId,long orgId){
		List<CoreOrg> orgs =  orgDao.queryOrgByUser(userId);
		if(orgs.isEmpty()){
			//没有赋值任何角色，默认给一个所在部门
			CoreOrg userOrg = orgDao.unique(orgId);
			orgs.add(userOrg);
		}
		return orgs;
	}
	
	
	
	public List<CoreUser> getAllUsersByRole(String role){
		return userDao.getUserByRole(role);
	}
	
	public CoreUser getUserByCode(String userName){
		CoreUser user = new CoreUser();
		user.setCode(userName);
		return userDao.templateOne(user);
	}
	
	public void update(CoreUser user){
		userDao.updateById(user);
	}
	
	public CoreOrg getOrgById(Long orgId){
		return orgDao.unique(orgId);
	}
	
	public CoreUser getUserById(Long userId){
		return userDao.unique(userId);
	}
	
	public List<String> getOrgCode(List<Long> orgIds){
		return orgDao.queryAllOrgCode(orgIds);
	}
}
